/*
 * @Author: sympsel sympsel@outlook.com
 * @Date: 2025-07-25 23:12:57
 * @LastEditors: sympsel sympsel@outlook.com
 * @LastEditTime: 2025-07-26 18:02:45
 * @FilePath: \work25_7_24\src\FileSort.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "universal.h"

void CreateNDate() {
    int n = 100;
    srand(time(NULL));
    const char* file = "lib/data.txt";
    FILE* fin = fopen(file, "w");
    if (fin == NULL) {
        perror("fopen error\n");
        return;
    }
    for (int i = 0; i < n; i++) {
        int x = rand();
        fprintf(fin, "%d\n", x);
    }
    fclose(fin);
}

void test1() {
    CreateNDate();
}

int compare_int(void* a, void* b) {
    return *(int*)a - *(int*)b;
}

void ReadNDataSortToFile(const char* fout, int n, const char* file1) {
    FILE* fin = fopen(file1, "w");
    if (fin == NULL) {
        perror("fopen error\n");
        return;
    }

    int x = 0;
    int* arr = MALLOC(int, n);
    int k = 0;
    for (int i = 0; i < n; i++) {
        fscanf(fout, "%d", &x);
        arr[k++] = x;
    }

    qsort(arr, n, sizeof(int), compare_int);

    for (int i = 0; i < n; i++) {
        fprintf(fin, "%d\n", arr[i]);
    }
    
    fclose(fin);
}

void MergeFile(const char* file1, const char* file2, const char* mfile) {

}

void test2() {


    const char* file1 = "lib/file1.txt";
    const char* file2 = "lib/file2.txt";
    const char* mfile = "lib/mfile.txt";

    FILE* fout = fopen("lib/data,txt", "r");
    if (fout == NULL) {
        perror("fopen error\n");
        return;
    }

    ReadNDataSortToFile(fout, 10, file1);
    ReadNDataSortToFile(fout, 10, file2);

    while (true) {
        MergeFile(file1, file2, mfile);
        remove(file1);
        remove(file2);
        
        rename(mfile, file1);

        ReadNDataSortToFile(fout, 10, file2);
    }
}

int main() {
    // test1();
    test2();
    return 0;
}